# --**coding:utf-8**--
# Create by author: hemq

import os, time
from PIL import ImageFile
from django.core.files import File
'''
遍历UploadedFile.chunks()，而不是使用read()，能确保大文件并不会占用系统过多的内存：
'''


def handle_upload_file(self, file):
    with open(file, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)


def handle_upload_file(file, filename):
    path = './baseapk/'  # 上传文件的保存路径，可以自己指定任意的路径
    if not os.path.exists(path):  # 若该路径不存在，则创建存储文件夹
        os.mkdir(path)
    with open(path + filename, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)


def _upload(file, path):
    """
    图片上传函数
    """
    if file:
        _n = "%d" % (time.time() * 1000)
        _f = time.strftime("%Y%m%d", time.localtime())

        file_name = _f + _n + ".jpg"
        path_file = os.path.join(path, file_name)
        parser = ImageFile.Parser()
        for chunk in file.chunks():
            parser.feed(chunk)
        img = parser.close()
        try:
            if img.mode != "RGB":
                img = img.convert("RGB")
            img.save(path_file, 'jpeg', quality=100)

        except:
            return None
        return file_name
    return None


def getVersionFromFile():
    """
    :return: 版本号
    """
    version = ''
    with open('versionFile.txt') as file:
        version = file.readline()
    return version


def deleteVersionFromFile():
    """   
    :return: 删除versionfile.txt
    """
    versionFilePath = './' + 'versionfile.txt'
    if os.path.exists(versionFilePath):
        os.remove(versionFilePath)
        return True
    else:
        return False


def getBaseApkPath():
    """ 
    :return: 获取母包路径
    """
    baseApkPath = []  # 获取母包路径
    for root, dirs, files in os.walk('./baseapk'):
        for file in files:
            if os.path.splitext(file)[1] == '.apk':
                baseApkPath.append(os.path.join(root, file))
    return baseApkPath


def getBaseApkName():
    """
    :return: 获取母包name
    """
    baseApkName = []  # 获取母包文件名
    for root, dirs, files in os.walk('./baseapk'):
        for file in files:
            if os.path.splitext(file)[1] == '.apk':
                baseApkName.append(os.path.join('', file))
    return baseApkName


def baseApkArchive():
    pass


def delChannelApkDir():
    """
    :return: 删除channelApk文件夹及其内容
    """
    dirPath = './channel/staticc/channelApk/'
    for root, dirs, files in os.walk(dirPath):
        for apkfile in files:
            os.remove(os.path.join(root, apkfile))
        os.rmdir(dirPath)

def creatChannelApk():
    # 创建文件夹
    channelApk = './channel/staticc/channelApk/'
    if not os.path.exists(channelApk):
        os.mkdir(channelApk)


